package com.wuliang.generate.common.sharding.configs;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.HashMap;
import java.util.Map;

/**
 * @author WuLiang
 */
@Slf4j
@Configuration
@EnableTransactionManagement
public class DruidConfig {

    @Bean
    public ServletRegistrationBean druidServlet() {
        log.info("开始Druid Servlet初始化配置...");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        Map<String, String> initParameters = new HashMap<>(8);
        //用户名
        initParameters.put("loginUsername", "wangh");
        //密码
        initParameters.put("loginPassword", "easted");
        // 禁用HTML页面上的“Reset All”功能
        initParameters.put("resetEnable", "false");
        // IP白名单 (没有配置或者为空，则允许所有访问)
        initParameters.put("allow", "127.0.0.1");
        // IP黑名单 (存在共同时，deny优先于allow)
        initParameters.put("deny", "");
        servletRegistrationBean.setInitParameters(initParameters);
        log.info("Druid Servlet初始化配置已完成...");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        log.info("初始化 Druid 过滤链");
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        log.info("druid 过滤链初始化完成");
        return filterRegistrationBean;
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.jpa")
    public JpaVendorAdapter jpaVendorAdapter() {
        return new HibernateJpaVendorAdapter();
    }

}
